const router = require('express').Router()
const {query} = require('../db')

// 获取角色列表
router.get('/auth', async (req, res) => {
  // 去顶层数据
  var sql = `select * from auths where pid=0`
  let outData = []
  let data = await query(sql)
  for (let i = 0; i < data.length; i++) {
    let id = data[i].id
    var sql = `select * from auths where pid=${id}`
    let childData = await query(sql)
    outData.push({
      ...data[i],
      children:childData
    })
  }
  res.send({
    code: 0,
    msg: 'ok',
    data: outData
  })
})


// 添加权限
router.post('/auth', async (req, res) => {
  const {name, ismenu = '1', pid = 0, route = ''} = req.body
  const sql = `insert into auths (name, ismenu, pid, route) 
  values ('${name}','${ismenu}',${pid},'${route}')`
  const ret = await query(sql)
  res.send({
    code: 0,
    msg: 'ok',
    data: {name, ismenu, pid, route}
  })
})

module.exports = router
